package com.joeyzh.table;

import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.TableLayout;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.joey.base.util.LogUtils;
import com.joey.base.util.ResourcesUtils;
import com.joey.base.util.SharedPreferenceUtils;
import com.joeyzh.R;
import com.joeyzh.base.BaseMvvmNoBarFragment;
import com.joeyzh.imagepicker.AddImageAdapter;
import com.joeyzh.imagepicker.ImagePickerFragment;
import com.joeyzh.imagepicker.utils.PickerConfig;
import com.joeyzh.utils.Base64Helper;
import com.joeyzh.utils.StringParseHelper;
import com.joeyzh.utils.TestJsonReader;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Joey on 2019/3/7.
 *
 * @author by Joey
 *         自定义表单布局
 */

public class BaseTableLogFragment extends BaseMvvmNoBarFragment<TableLogEntity, BaseTableViewModel, BaseTableLogPresenter> implements LogSubmitDelegate, ILogPresenterCallback {

    /**
     * 当前环节的流程节点
     */
    private String testPath;
    private TableLayout tableLayout;
    protected List<ImagePickerFragment> pickerFragments = new ArrayList<>();

    public BaseTableLogFragment() {
        Bundle args = new Bundle();
        setArguments(args);
    }

    public static BaseTableLogFragment newInstance(String flowKey) {

        Bundle args = new Bundle();
        args.putString("path", flowKey);
        BaseTableLogFragment fragment = new BaseTableLogFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onChildViewCreate(View parent, @Nullable Bundle savedInstanceState) {
        View root = View.inflate(getActivity(), R.layout.ifr_fragment_log_base, null);
        tableLayout = root.findViewById(R.id.tl_log_content);

        return root;
    }

    @Override
    public void initData() {
        super.initData();
        presenter.setLogPresenterCallback(this);
        viewModel.bindAllViews();
        loadSuccess(entity);
        String saveInfo = SharedPreferenceUtils.getInstance().getString(testPath);
        entity.setItemListJson(saveInfo);
        if (!TextUtils.isEmpty(saveInfo)) {
            presenter.updateItemValue(entity);
        }
    }

    @Override
    public BaseTableLogPresenter createPresenter(BaseTableViewModel viewModel) {
        if (presenter != null) {
            return presenter;
        }
        return new BaseTableLogPresenter(getActivity(), viewModel);
    }

    @Override
    public BaseTableViewModel createViewModel(TableLogEntity entity) {
        if (viewModel != null) {
            return viewModel;
        }
        return new BaseTableViewModel(tableLayout, entity);
    }

    public <T extends BaseTableLogPresenter> void setPresenter(T presenter) {
        this.presenter = presenter;
    }

    @Override
    public TableLogEntity getEntity() {
        if (entity != null) {
            return entity;
        }
        testPath = getArguments().getString("path");
        String tableJson = TestJsonReader.getString(getActivity(), testPath);
        JsonObject root = new Gson().fromJson(tableJson, JsonObject.class);
        TableLogEntity item = new Gson().fromJson(root.get("value"), TableLogEntity.class);
        return item;
    }


    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void submit(final boolean autoCheck) {
        presenter.submit();
    }

    @Override
    public void loadSuccess(TableLogEntity entity) {
        this.entity = entity;
        pickerFragments.clear();
        PickerConfig config = new PickerConfig().setPickerNumColumns(3);

        // 设置设置图片
        if (viewModel.getImageItems() != null && viewModel.getImageItems().size() > 0) {
            FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
            int i = 0;
            for (TableLogItemEntity item : viewModel.getImageItems()) {
                ImagePickerFragment fragment = ImagePickerFragment.newInstance(item.getText()).initConfig(config);
                if (entity.isEditable()) {
                    fragment.setEditable(item.isEnable());
                } else {
                    fragment.setEditable(entity.isEditable());
                }
                pickerFragments.add(fragment);
                transaction.replace(ResourcesUtils.getId("fl_image_content_" + i), fragment, item.getParamCode());
                i++;
            }
            transaction.commit();
        }
        //刷新配置信息
        if (!viewModel.getDictItems().isEmpty()){
            presenter.loadBaseInfo(viewModel.getDictItems().values());
        }
    }

    public void save() {
        viewModel.bindBeanValues();
        List<TableLogItemEntity> data = new ArrayList<>(viewModel.getValues());
        try {
            //拼接多选
            bindMutiSelected();
            for (TableLogItemEntity item : viewModel.getMutiItems()) {
                data.addAll(item.getParamArray());
            }
            //拼接自定义
            bindCustomValue();
            for (TableLogItemEntity item : viewModel.getcustomItems()) {
                data.addAll(item.getParamArray());
            }
            //拼接图片
            bindImage(false);
            for (TableLogItemEntity item : viewModel.getImageItems()) {
                if (item.getParamArray() == null || item.getParamArray().isEmpty()) {
                    continue;
                }
                for (Object path : item.getParamArray()) {
                    data.add(new TableLogItemEntity(path.toString(), item.ParamCode));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (entity.isEditable()) {
            String json = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(data);
            SharedPreferenceUtils.getInstance().putString(testPath, json);
            SharedPreferenceUtils.getInstance().putLong(testPath + "Time", System.currentTimeMillis());
        } else {
            SharedPreferenceUtils.getInstance().remove(testPath);
            SharedPreferenceUtils.getInstance().remove(testPath + "Time");
        }
    }

    public void checkoutInfo(final boolean forceChecked) {
        viewModel.bindBeanValues();
        /**
         * 绑定视图
         */
        new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... voids) {
                bindImage(true);
                return bindMutiSelected() && bindCustomValue();
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                showDialogMessage("正在压缩图片，请稍等...");
            }

            @Override
            protected void onPostExecute(Boolean checkResult) {
                LogUtils.e("onPostExecute");
                dismiss();
                if (!forceChecked) {
                    submit(forceChecked);
                } else if (presenter.checkoutInfo()) {
                    submit(forceChecked);
                }
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    protected boolean bindCustomValue() {
        return true;
    }

    protected boolean bindMutiSelected() {
        return true;
    }

    protected void bindImage(boolean convert2Base64) {
        // 解析图片
        if (pickerFragments.isEmpty()) {
            return;
        }
        for (int i = 0; i < pickerFragments.size(); i++) {
            TableLogItemEntity entity = viewModel.getImageItems().get(i);
            ArrayList base64Arr = new ArrayList();
            ArrayList<String> imgs = new ArrayList<>(pickerFragments.get(i).getImgsList());
            entity.setParamArray(new ArrayList<TableLogItemEntity>());
            if (imgs.isEmpty()) {
                continue;
            }
            for (String path : imgs) {
                if (TextUtils.isEmpty(path) || path.equalsIgnoreCase(AddImageAdapter.EMPTY_PATH)) {
                    continue;
                }
                // 拼接图片
                if (path.indexOf(";base64,") < 0 && convert2Base64) {
                    String base64 = Base64Helper.formatBase64Str(path, true).toString();
                    // 表示转化成base64
                    base64Arr.add(base64);
                } else {
                    base64Arr.add(path);
                }
            }
            entity.setParamArray(base64Arr);
        }

    }

    @Override
    public void submitSuccess() {
        SharedPreferenceUtils.getInstance().remove(testPath);
        SharedPreferenceUtils.getInstance().remove(testPath + "Time");
    }

    @Override
    public void updateSuccess(TableLogEntity entity) {
        try {
            updateImages(entity);
            updateCustom(entity);
        } catch (Exception e) {

        }

    }

    protected void updateImages(final TableLogEntity entity) {
        // 解析图片数据
        final List<TableLogItemEntity> values = entity.getImageValues();
        if (values == null || values.isEmpty()) {
            return;
        }
        /**
         * 遍历设置照片
         */
        new AsyncTask<Void, Void, List<List<String>>>() {
            @Override
            protected List<List<String>> doInBackground(Void... voids) {
                List<List<String>> basePathAray = new ArrayList<>();
                for (int i = 0; i < values.size(); i++) {
                    TableLogItemEntity image = values.get(i);
                    if (image.getParamArray() == null) {
                        /**
                         * 如果图片不存在，那么从暂存的数据中取数数据
                         */
                        basePathAray.add(StringParseHelper.parseValueArrayBase64(entity.getItemListJson(), "ParamValue", image.getParamCode()));
                    } else {
                        basePathAray.add(image.getParamArray());
                    }
                }
                return basePathAray;
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                showDialogMessage("正在加载图片...");
            }

            @Override
            protected void onPostExecute(List<List<String>> base64Array) {
                LogUtils.e("onPostExecute");
                for (int i = 0; i < base64Array.size(); i++) {
                    if (entity.isEditable()) {
                        pickerFragments.get(i).setEditable(values.get(i).isEnable());
                    } else {
                        pickerFragments.get(i).setEditable(entity.isEditable());
                    }
                    pickerFragments.get(i).clear();
                    pickerFragments.get(i).addPathList(base64Array.get(i));
                    pickerFragments.get(i).getAddAdapter().notifyDataSetChanged();
                }
                dismiss();
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    }


    protected void updateCustom(TableLogEntity entity) {

    }

}
